<?php
namespace App\Http\Controllers\User\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{

    public function showLoginForm()
    {
        return view('user.auth.login');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            $request->session()->regenerate();
            $callback = $request->get('callback', route('user.dashboard'));
            return redirect($callback);
        }
        return redirect()->back()->withErrors(['username' => '用户名和密码不匹配']);
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt([
            $this->username($request)   => $request->input('username'),
            'password'                  => $request->input('password')
        ], $request->filled('is_remember'));
    }

    protected function validateLogin(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string'
        ], [
            'username.required' => '登录用户不能为空',
            'username.string'   => '用户名格式错误',
            'password.required' => '请输入密码',
            'password.string'   => '密码格式错误'
        ]);
    }

    protected function username(Request $request)
    {
        $username = $request->input('username');
        if (preg_match('/^1[1-9]\d{9}$/', $username)) {
            return 'phone';
        }
        if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
            return 'email';
        }
        return 'username';
    }

    protected function guard()
    {
        return Auth::guard('user');
    }
}
